﻿Public Class GeneralForm

    Dim wassaved As Boolean
    Dim wherewassaved As String

    Private Sub GeneralForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ' Проверка запуска
        Dim file As String = Command$()
        If file = "" Then

        Else
            file = Replace(file, Chr(34), "")
            Dim fileext = System.IO.Path.GetExtension(file)
            If fileext = ".gcp" Then
                Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator"
                System.IO.Directory.CreateDirectory(path)
                System.IO.Directory.CreateDirectory(path + "\tmp")
                Using zip1 As Ionic.Zip.ZipFile = Ionic.Zip.ZipFile.Read(file)
                    Dim y As Ionic.Zip.ZipEntry
                    ' here, we extract every entry, but we could extract    
                    ' based on entry name, size, date, etc.   
                    For Each y In zip1
                        y.Extract(path + "\tmp", Ionic.Zip.ExtractExistingFileAction.OverwriteSilently)
                    Next
                End Using
                Try

                Catch ex As Exception

                End Try
            Else
                MsgBox("Файл, с расширением " + fileext + ", не поддерживается Gadget Creator.", 48, "Открытие файла...")
            End If
        End If

    End Sub
    Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click
        If MsgBox("Все несохранённые данные будут стёрты. Продолжить?", 36, "Gadget Creator Beta Preview 2") = MsgBoxResult.Yes Then

            tabcontrol.TabPages.Clear()

            ' Создание редактора гаджета(начало)

            Dim gadgetpage As New TabPage
            gadgetpage.Text = "Гаджет"
            Dim htmlbox As New FastColoredTextBoxNS.FastColoredTextBox
            htmlbox.Language = FastColoredTextBoxNS.Language.HTML
            htmlbox.Text = My.Settings.htmlsyntax
            htmlbox.Dock = DockStyle.Fill
            gadgetpage.Controls.Add(htmlbox)
            gadgetpage.Name = "gadget.html"
            tabcontrol.TabPages.Add(gadgetpage)

            ' Создание редактора гаджета(конец)

            ' Создание редактора настроек(начало)

            Dim setpage As New TabPage
            setpage.Text = "Страница настроек"
            Dim setbox As New FastColoredTextBoxNS.FastColoredTextBox
            setbox.Language = FastColoredTextBoxNS.Language.HTML
            setbox.Text = "" ' Заменить на текст страницы настроек
            setbox.Dock = DockStyle.Fill
            setpage.Controls.Add(setbox)
            setpage.Name = "settings.html"
            tabcontrol.TabPages.Add(setpage)

            ' Создание редактора настроек(конец)

            tabcontrol.SelectedTab = gadgetpage
            wassaved = False
        End If
    End Sub
    Private Sub СвойстваГаджетаToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles СвойстваГаджетаToolStripMenuItem.Click
        GadgetSetForm.Show()
    End Sub

    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
        Dim ofd As New OpenFileDialog
        ofd.Filter = "Проекты Gadget Creator|*.gcp"
        ofd.Title = "Открыть проект Gadget Creator"
        If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim fileext As String = System.IO.Path.GetExtension(ofd.FileName)
            If fileext = ".gcp" Then
                Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp"
                Using zip1 As Ionic.Zip.ZipFile = Ionic.Zip.ZipFile.Read(ofd.FileName)
                    Dim y As Ionic.Zip.ZipEntry
                    ' here, we extract every entry, but we could extract    
                    ' based on entry name, size, date, etc.   
                    For Each y In zip1
                        y.Extract(path, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently)
                    Next
                End Using
                Try
                    If System.IO.File.Exists(path + "\gadget.xml") = False Then
                        MsgBox("Проект повреждён и не может быть открыт!", 64, "Открытие проекта...")
                        Exit Sub
                    Else
                        If System.IO.File.Exists(path + "\gadget.html") = False Then
                            Dim creategadgetfile As New System.IO.StreamWriter(path)
                            creategadgetfile.Write(My.Settings.htmlsyntax)
                            creategadgetfile.Close()
                            Dim gadgetpage As New TabPage
                            gadgetpage.Name = "gadget.html"
                            gadgetpage.Text = "Гаджет"
                            Dim htmlbox As New FastColoredTextBoxNS.FastColoredTextBox
                            htmlbox.Language = FastColoredTextBoxNS.Language.HTML
                            htmlbox.Text = My.Settings.htmlsyntax
                            htmlbox.Dock = DockStyle.Fill
                            gadgetpage.Controls.Add(htmlbox)
                            tabcontrol.TabPages.Add(gadgetpage)
                        Else
                            Dim opengadgetfile As New System.IO.StreamReader(path + "\gadget.html")
                            Dim gadgetpage As New TabPage
                            gadgetpage.Name = "gadget.html"
                            gadgetpage.Text = "Гаджет"
                            Dim htmlbox As New FastColoredTextBoxNS.FastColoredTextBox
                            htmlbox.Language = FastColoredTextBoxNS.Language.HTML
                            htmlbox.Text = opengadgetfile.ReadToEnd()
                            opengadgetfile.Close()
                            htmlbox.Dock = DockStyle.Fill
                            gadgetpage.Controls.Add(htmlbox)
                            tabcontrol.TabPages.Add(gadgetpage)
                        End If
                    End If
                Catch ex As Exception
                    MsgBox(ex.Message, 16, "Ошибка")
                End Try

            Else

                MsgBox("Файл, с расширением " + fileext + ", не является проектом Gadget Creator")

            End If

        End If
    End Sub

    Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
        If wassaved = True Then

        End If
        Try
            Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp"
            tabcontrol.SelectedIndex = 0
            For Each TabPage In tabcontrol.TabPages
                Dim writer As New System.IO.StreamWriter(path + "\" + tabcontrol.SelectedTab.Name, False, System.Text.Encoding.GetEncoding(1251))
                writer.Write(CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Text)
                writer.Close()
                tabcontrol.SelectedIndex = +1
            Next
        Catch ex As Exception

        End Try
    End Sub

    Private Sub UndoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UndoToolStripMenuItem.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Undo()
    End Sub

    Private Sub RedoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RedoToolStripMenuItem.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Redo()
    End Sub

    Private Sub cut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cut.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Cut()
    End Sub

    Private Sub copy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles copy.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Copy()
    End Sub

    Private Sub paste_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles paste.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Paste()
    End Sub

    Private Sub selectall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles selectall.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).SelectAll()
    End Sub

    Private Sub КомпилироватьToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles КомпилироватьToolStripMenuItem.Click

    End Sub

    Private Sub ОбзорФайловToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browser.Click
        If browser.Checked = True Then
            browser.Checked = False
            browsefiles.Visible = False
            refreshfiles()
        Else
            browser.Checked = True
            browsefiles.Visible = True
            refreshfiles()
        End If
    End Sub
    Public Sub refreshfiles()
        Try
            ListView1.Items.Clear()
            Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp"
            Dim folderInfo As New IO.DirectoryInfo(path)
            Dim arrFilesInFolder() As IO.FileInfo
            Dim fileInFolder As IO.FileInfo
            arrFilesInFolder = folderInfo.GetFiles("*.html")
            For Each fileInFolder In arrFilesInFolder
                ListView1.Items.Add(fileInFolder.Name).StateImageIndex = 0
            Next
            arrFilesInFolder = folderInfo.GetFiles("*.xml")
            For Each fileInFolder In arrFilesInFolder
                ListView1.Items.Add(fileInFolder.Name).StateImageIndex = 1
            Next
            arrFilesInFolder = folderInfo.GetFiles("*.js")
            For Each fileInFolder In arrFilesInFolder
                ListView1.Items.Add(fileInFolder.Name).StateImageIndex = 2
            Next
            arrFilesInFolder = folderInfo.GetFiles("*.txt")
            For Each fileInFolder In arrFilesInFolder
                ListView1.Items.Add(fileInFolder.Name).StateImageIndex = 3
            Next
            arrFilesInFolder = folderInfo.GetFiles("*.css")
            For Each fileInFolder In arrFilesInFolder
                ListView1.Items.Add(fileInFolder.Name).StateImageIndex = 4
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged
        tabcontrol.SelectedIndex = 0
        Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp"
        If ListView1.SelectedItems.Count > 0 Then
            Dim type = ListView1.FocusedItem.Text
            If type = "gadget.xml" Then
                MsgBox("В режиме 'Простой' нельзя редактировать файл gadget.xml в редакторе", 64, "Редактирование")
                GadgetSetForm.Show()
            End If
            If type.EndsWith(".html") = True Then
                If tabcontrol.TabPages.ContainsKey(type) = True Then
                    tabcontrol.SelectTab(type)
                Else
                    Dim editor As New TabPage
                    editor.Text = ListView1.FocusedItem.Text
                    editor.Name = ListView1.FocusedItem.Text
                    Dim htmlbox As New FastColoredTextBoxNS.FastColoredTextBox
                    htmlbox.Language = FastColoredTextBoxNS.Language.HTML
                    Dim reader As New System.IO.StreamReader(path + "\" + ListView1.FocusedItem.Text, System.Text.Encoding.GetEncoding(1251))
                    htmlbox.Text = reader.ReadToEnd
                    reader.Close()
                    htmlbox.Dock = DockStyle.Fill
                    editor.Controls.Add(htmlbox)
                    tabcontrol.TabPages.Add(editor)
                    tabcontrol.SelectedTab = editor
                End If
            End If
            If type.EndsWith(".js") = True Then
                If tabcontrol.TabPages.ContainsKey(type) = True Then
                    tabcontrol.SelectTab(type)
                Else
                    Dim editor As New TabPage
                    editor.Text = ListView1.FocusedItem.Text
                    editor.Name = ListView1.FocusedItem.Text
                    Dim jsbox As New FastColoredTextBoxNS.FastColoredTextBox
                    jsbox.Language = FastColoredTextBoxNS.Language.JS
                    Dim reader As New System.IO.StreamReader(path + "\" + ListView1.FocusedItem.Text, System.Text.Encoding.GetEncoding(1251))
                    jsbox.Text = reader.ReadToEnd
                    reader.Close()
                    jsbox.Dock = DockStyle.Fill
                    editor.Controls.Add(jsbox)
                    tabcontrol.TabPages.Add(editor)
                    tabcontrol.SelectedTab = editor
                End If
            End If
            If type.EndsWith(".css") = True Then
                If tabcontrol.TabPages.ContainsKey(type) = True Then
                    tabcontrol.SelectTab(type)
                Else
                    Dim editor As New TabPage
                    editor.Text = ListView1.FocusedItem.Text
                    editor.Name = ListView1.FocusedItem.Text
                    Dim htmlbox As New FastColoredTextBoxNS.FastColoredTextBox
                    htmlbox.Language = FastColoredTextBoxNS.Language.Custom
                    Dim reader As New System.IO.StreamReader(path + "\" + ListView1.FocusedItem.Text, System.Text.Encoding.GetEncoding(1251))
                    htmlbox.Text = reader.ReadToEnd
                    reader.Close()
                    htmlbox.Dock = DockStyle.Fill
                    editor.Controls.Add(htmlbox)
                    tabcontrol.TabPages.Add(editor)
                    tabcontrol.SelectedTab = editor
                End If
            End If
        End If
    End Sub

    Private Sub НовыйФайлToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles НовыйФайлToolStripMenuItem.Click
        CreateFile.Show()
    End Sub
End Class
